package org.wltea.analyzer.help;

import org.elasticsearch.common.io.PathUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class Utils {
    /**
     * closeStatement
     *
     * @param statement statement
     */
    public static void closeStatement(Statement statement) {
        try {
            if (statement != null && !statement.isClosed()) {
                statement.close();
            }
        } catch (SQLException exception) {
            throw new RuntimeException(exception);
        }
    }

    /**
     * closeResultSet
     *
     * @param resultSet resultSet
     */
    public static void closeResultSet(ResultSet resultSet) {
        try {
            if (resultSet != null && !resultSet.isClosed()) {
                resultSet.close();
            }
        } catch (SQLException exception) {
            throw new RuntimeException(exception);
        }
    }

    /**
     * closeInputStream
     *
     * @param inputStream inputStream
     */
    public static void closeInputStream(InputStream inputStream) {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException exception) {
                throw new RuntimeException(exception);
            }
        }
    }

    /**
     * getProperties
     *
     * @param fileName fileName
     * @param dictRoot dictRoot
     * @return Properties
     */
    public static Properties getProperties(String fileName, String dictRoot) {
        Properties properties = new Properties();
        InputStream inputStream = null;
        try {
            inputStream = Files.newInputStream(PathUtils.get(dictRoot, fileName).toFile().toPath());
            properties.load(inputStream);
        } catch (IOException exception) {
            throw new RuntimeException(exception);
        } finally {
            closeInputStream(inputStream);
        }
        return properties;
    }
}
